package cn.admin.remoting.serialize.impl.hessian;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AliEnumSerializer extends AbstractSerializer {

    private Method name;

    public AliEnumSerializer(Class<?> cl) {
        try {
            this.name = cl.getDeclaredMethod("getName");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void writeObject(Object enumObj, AbstractHessianOutput out) throws IOException {

        if (enumObj != null) {
            if (!out.addRef(enumObj)) {
                Class<?> cl = enumObj.getClass();
                String name;

                try {
                    name = (String) this.name.invoke(enumObj, (Object[]) null);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }

                out.writeMapBegin(cl.getName());
                out.writeString("name");
                out.writeString(name);
                out.writeMapEnd();
            }
        }

    }

}
